<!-- 一键跟单 -->
<template>
  <div>
    <scroller class="all">
      <div class="wrapper" v-if="api">
        
        <!--服务器-->
        <VServer class="server" ref="server"></VServer>

        <!--每日佣金-->
        <div class="title">
          <div class="title-line main1"></div>
          <text class="font28 text1">{{T('跟单佣金')}}</text>
        </div>
        <div class="wages bg2">
          <text class="font24 text3">{{T('跟单佣金')}}</text>
          <div class="all"></div>
          <text class="font24 text2">{{commission +' VTN' + '/' + '日' + '（' + (isVtnEquity ? T('含提现权益') : T('不含提现权益')) + '）'}}</text>
          <LImage class="texture1" :src="config.img('texture1.png')"></LImage>
        </div>

        <!--API-->
        <div class="title" @click="apiClick">
          <div class="title-line main1"></div>
          <text class="font28 text1">{{api.apiName}}</text>
          <div class="all"></div>
          <text class="font24 main-t1">{{T('账户切换')+'>>   '}}</text>
        </div>

        <!--投入-->
        <VInput v-model="investNum" :placeholder="T('跟投金额')" :optional="true" :unit="investCoin"></VInput>
      
        <!--内凹界面-余额、提示、启动按钮-->
        <div class="concave">
          <div class="height20"></div>
          <text class="font24 text2">{{T('可用')+'：'+moneyNum + ' ' + investCoin}}</text>

          <div class="height20"></div>
          <text class="font20 text3 money-tipe">{{T('为保证策略顺利启动执行，本策略跟单投入资金限制')+minInvest+'-'+maxInvest+" "+investCoin}}</text>
          <div class="height40"></div>
          <div class="but main1" @click="upClick">
            <text class="font32 text1">{{T('启动')}}</text>
          </div>
        </div>
        
        <!--提示-->
        <div>
          <text class="font28 main-t1 tipe-text">{{T('提示')}}</text>
          <text class="font24 text3 tipe-text" >{{T("1、付费方式为固定佣金的，启动跟单后每日自动支付佣金给发起者。")}}</text>
          <text class="font24 text3 tipe-text" >{{T("2、付费方式为盈利分成的，启动跟单时将在您的钱包消费账户中冻结相应数额的VTN，结算时按VTN时价从保证金中扣除分成金额，支付金额最高不超过保证金全额；结算后如果跟单未停止，消费账户将再次冻结一笔保证金；停止跟单后保证金解冻。")}}</text>
          <text class="font24 text3 tipe-text" >{{T("3、发起者停止跟单即停止支付费用。")}}</text>
          <text class="font24 text3 tipe-text" >{{T("4、您也可以提前终止跟单，终止后即停止支付费用。")}}</text>
          <text class="font24 text3 tipe-text" >{{T("5、为保证跟单持续执行请确保您的消费账户中拥有足够的VTN。")}}</text>
        </div>
        
        <!--风险提示-->
        <div>
          <div class="risk bk1">
            <text class="font24 text3 risk-text">{{T('任何策略不能保证其在未来的正盈利性，过往数据不预示未来表现，投资有风险，请谨慎选择。请确保本人完全理解并可以承担相关风险可能带来的结果。')}}</text>
          </div>
          <div class="risk-title-bg">
            <div class="risk-title bg1">
              <text class="font28 udRed-t1">{{T('风险提示')}}</text>
            </div>
          </div>
        </div>
      </div>
    </scroller>


    <!--确认弹窗-->
    <div class="confirm-content" v-if="confirm">
      <div class="confirm-bg" v-if="confirm">
        <text class="confirm-title-text36">{{T('确认跟单')}}</text>
        <div class="height30"></div>
        <div class="row">
          <text class="confirm-title-text30">{{T('佣金')+"："}}</text>
          <text class="confirm-value-text">{{commission +' VTN' + '/' + '日'+ '（' + (isVtnEquity ? T('含提现权益') : T('不含提现权益')) + '）'}}</text>
        </div>
        <div class="height20"></div>
        <div class="row">
          <text class="confirm-title-text30">{{T('投入金额')+"："}}</text>
          <text class="confirm-value-text">{{investNum + ' ' + investCoin}}</text>
        </div>
        <div class="row">
          <text @click="confirm=!confirm" class="confirm-but-text">{{T('取消')}}</text>
          <text @click="confirmOK" class="confirm-but-text">{{T('确认')}}</text>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

//组件
import VServer from "@/up/view/VServer.vue";
import VInput from "@/public/view/VInput.vue";

//功能
import config from "@/_js/config";
import math from "@/_js/math";
import modal from "@/_js/modal";
import broadcast from "@/_js/broadcast";
import navigator from "@/_js/navigator";
import API from "@/_js/api";
import mParam from "@/up/amParam";


const weexFunction = weex.requireModule("WeexFunction");
import weexHttp from "@/_js/https"; ;
const globalEvent = weex.requireModule('globalEvent');

import I18N from "@/_i18n/i18n";
var T = I18N.t;
weexFunction.setTitle(T("一键跟单"));

export default {
  
  components: {
    VServer,
    VInput,
  },

  data() {
    return {
      T:T,
      config:config,
      math:math,
      isUp:false, //turn已经启动过合约

      confirm:false, //true 显示确认弹窗

      
      commission:"", //佣金
      isVtnEquity:true, //tur含提现权益

      executeId:"", //执行id
      strategyId:"", //策略id
      exchangeName:'', //交易所名称
      counterCoin:'', //交易币
      baseCoin:'', //本币
      minInvest:"",//最小投资数量
      maxInvest:"",//最大投资数量
      investCoin:'', //投资币

      api: undefined, //API
      investNum:'', //投资数量
      moneyNum:'', //可用数量
    };
  },

  mounted() {

    var commission = navigator.getParam("commission");
    this.commission = math.xiaoShuDelete0(commission);
    this.isVtnEquity = navigator.getParam("isVtnEquity");
    
    this.executeId =navigator.getParam("executeId");
    this.strategyId = navigator.getParam("strategyId");
    this.counterCoin = navigator.getParam("counterCoin");
    this.baseCoin = navigator.getParam("baseCoin");
    this.investCoin = navigator.getParam("investCoin");

    this.minInvest = navigator.getParam("minInvest");
    this.maxInvest = navigator.getParam("maxInvest");

    var exchangeName = navigator.getParam("exchangeName");
    this.httpsMarketDetail(exchangeName, this.investCoin);

    //Api更新通知
    var self = this;
    globalEvent.addEventListener("apiUp",(e)=>{
      if (self.api && self.api.apiId == '') {
        return;
      }
      API.getApi(self.api.apiId, 'all', (api)=>{
        self.api = api;
        self.upApiMoney();
      });
    });
  },

  methods: {
    
    //初始化API
    initApi(exchangeName) {
      API.getMockApi(exchangeName, (api)=>{
        API.getApis('YES', 'all', exchangeName, (apis)=>{
            api = this.getMockApi(api);
            for (let index = 0; index < apis.length; index++) {
              var data = apis[index];
              if (!data.isFundApi) {
                api = apis[index];
                break;
              }
            }
            this.apiChange(api);
        });
      });
    },

    /********************************** HTTP*/
    //http查询币种行情价
    httpsMarketDetail(exchangeName, coin) {

      if (coin == 'USDT') {
          this.upInvestLimit('1');
          this.initApi(exchangeName);
        return;
      }

      modal.showLoad();
      var param = {'exchangeName': exchangeName,
                  'baseCoin': "USDT", 
                  'counterCoin': coin};
      weexHttp.post("quoteV2/queryMarketDetail",param,true,(data) => {
        modal.hideLoad();
        if (data.status == 200) {
          data = data.data;
          var usdPrice = data.usdPrice;//当前价格
          this.upInvestLimit(usdPrice);
          this.initApi(exchangeName);
        } else {
          modal.toast(data.msg);
        }
      });
    },

    //http跟单
    httpFollw(){
      
      modal.showLoad();
      var server = this.$refs.server.server;
      var address = server ? server.innerIp : '';

      var param = {'address':address,
                   'investNum':this.investNum,
                   'executeId':this.executeId, 
                   'strategyId':this.strategyId};
      mParam.getApiParam(this.api, (apiMap)=>{
        param = Object.assign(param, apiMap);
        weexHttp.postX("follow/createMyFollowStrategy",param,true,(data) => {
          modal.hideLoad();
          if (data.status == 200) {
            
              modal.toast(T('跟单成功'));
              weexFunction.setShowTabBar(1);
              weexFunction.postNotificationName('StrategyShow', {'index':0});
              setTimeout(() => {
                broadcast.send('UpShow', {'index':1});
                broadcast.send(broadcast.EXECUTE_UPDATE);
                navigator.back(2);
              }, 500);
          }else {
            modal.toast(data.msg);
          }
        });
      });
    },
    
    //http策略-启动过合约策略
    httpCheckContract(){
      if (this.api.apiId == '') {
        this.isUp = false;
        return;
      }

      var param = {'apiId':this.api.apiId,  
                   'exchangeName':this.api.exchangeName};
      weexHttp.post("contract/querySpotPermission",param,true,(data)=>{
        if(data.status == 200){
          var data = data.data;
          this.isUp = data.isStartStrategy;
          if (this.isUp) {
            this.tipeUpCoin();
          }
        } else {            
          this.isUp = false;
        }
      });
    },
    
    /********************************** 其他*/
    //提示启动过该币种
    tipeUpCoin(){
      var tipe = T('单个统一账户只支持一个合约策略且执行合约策略时不可执行币币策略，&{1}账户已有执行中的合约策略，您可前往执行列表查看。');
      tipe = tipe.replace("&{1}", this.api.apiName);
      modal.alert(tipe,()=>{
      });
    },

    //获取模拟API
    getMockApi(api) {

      var apiName = api.exchangeName + '-' + T('模拟账户');
      var mockApi = {'exchangeName':api.exchangeName,
                    'exchangeId':api.exchangeId,
                    'apiName':apiName,
                    'tradeFee':api.tradeFee,
                    'apiId':''};
      return mockApi;
    },

    //api改变
    apiChange(api) {
      
      this.api = api;
      this.investNum ='';
      this.upApiMoney();
      API.synchroCoin(this.api.apiId, this.investCoin);
      this.httpCheckContract();
    },

    //更新投入限制
    upInvestLimit(usdPrice) {
      var xiaoshu = math.getCoin(this.investCoin);
      this.minInvest = math.chu(this.minInvest, usdPrice, xiaoshu, 2);
      this.maxInvest = math.chu(this.maxInvest, usdPrice, xiaoshu, 2);
    },
    
    //更新可用数量
    upApiMoney() {
      
      var xiaoshu = math.getCoin(this.investCoin);
      var num =  '0';
      if (this.api.apiId == '') {
        num = this.maxInvest;
      } else {

        for (let index = 0; index < this.api.accountAssets.length; index++) {
          var assets = this.api.accountAssets[index];
          if (assets.currency == this.investCoin) {
            num = math.xiaoshu(assets.availableReal, xiaoshu, 2);
            break;
          }
        }
      }
      this.moneyNum = math.getNumber(num) < 0 ? '0' : num;
    },
    /********************************** 点击触发*/
    //API
    apiClick(){
      
      var param = this.api.apiId == '' 
      ? {'exchangeId':this.api.exchangeId, 'menu':1, 'supports':this.api.exchangeName} 
      : {'apiId':this.api.apiId, 'menu':0, 'supports':this.api.exchangeName};
      navigator.openDialog('up/SelectApi', param);

      broadcast.subscribeOnce('SelectApi', (api)=>{
        api = api.apiId ? api : this.getMockApi(api);
        this.apiChange(api);
      });
    },

    //确认跟单
    confirmOK() {
      this.httpFollw();
    },

    //启动
    upClick() {
      
      //启动过OkexV5合约
      if (this.isUp) {
        this.tipeUpCoin();
        return;
      }

      if(this.investNum.length == 0){
        modal.toast(T("请输入跟投金额"));
        return;
      }

      if(math.getNumber(this.investNum) > math.getNumber(this.moneyNum)){
        modal.toast(T("可用余额不足"));
        return;
      }

      if(math.getNumber(this.investNum) > math.getNumber(this.maxInvest)){        
        modal.toast(T("最多跟投&{1}&{2}").replace("&{1}", this.maxInvest).replace("&{2}", this.investCoin));
        return;
      }

      if(math.getNumber(this.investNum)  < math.getNumber(this.minInvest)){
        modal.toast(T("最少跟投&{1}&{2}").replace("&{1}", this.minInvest).replace("&{2}", this.investCoin));
        return;
      }

      this.confirm = true;
    },
  },
};
</script>

 
<style src="@/_css/style.css"></style>
<style scoped>
.wrapper {
  padding-left: 20px;
  padding-right: 20px;
}

.server {
  margin-top: 40px;
}

.title {
  flex-direction: row;
  align-items: center;
  padding-top: 20px;
  padding-bottom: 20px;

  margin-top: 20px;
}
.title-line {
  width: 6px;
  height: 28px;
  border-radius: 3px;

  margin-right: 16px;
}

.wages {
  flex-direction: row;
  padding-left: 40px;
  padding-right: 40px;
  padding-top: 20px;
  padding-bottom: 20px;
}

.money-tipe{
  line-height: 36px;
}

.concave {
  padding-left: 20px;
  padding-right: 20px;
}

.but {
  flex-direction: row;
  justify-content: center;
  align-items: center;
  height: 80px;
  border-radius: 4px;

  margin-top: 40px;
  margin-bottom: 60px;
}

.tipe-text{
  line-height: 52px;
}

.risk {
  justify-content: center;
  width: 710px;
  border-width: 2px;
  padding-top: 30px;
  padding-left: 20px;
  padding-right: 20px;
  padding-bottom: 20px;
  
  margin-top: 80px;
  margin-bottom: 40px;
}
.risk-text {
  line-height: 44px;
}
.risk-title-bg {
  position: absolute;
  flex-direction: row;
  justify-content: center;
  width: 710px;
  top: 60px;
}
.risk-title {
  flex-direction: row;
  align-content: center;
  height: 40px;
  padding-left: 60px;
  padding-right: 60px;
}

.height20{
  height: 20px;
}
.height30 {
  height: 30px;
}


/*确认弹窗*/
.confirm-content{
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: absolute;
  width:750px;
  z-index: 9;
  top:0;
  right: 0;
  bottom:0;
  left:0;
  background-color:rgba(0,0,0,0.4);
}
.confirm-bg{
  width:630px;
  background-color:rgba(39,43,46,1);
  border-radius:4px;
  padding: 40px 40px 0px 40px;
}
.confirm-title-text36{
  flex: 1;
  text-align: center;
  height:48px;
  line-height:48px;
  font-size:36px;
  font-family:PingFangSC-Medium;
  color:rgba(255,255,255,1);
}
.confirm-title-text30{
  height:40px;
  line-height:40px;
  font-size:30px;
  font-family:PingFangSC-Regular;
  color:rgba(144,154,180,1);
}
.confirm-value-text{
  font-size:30px;
  font-family:PingFangSC-Regular;
  color:rgba(255,255,255,1);
}
.confirm-but-text{
  flex: 1;
  text-align: center;
  height:120px;
  line-height:120px;
  font-size:30px;
  font-family:PingFangSC-Medium;
  color:rgba(10,154,240,1);
}
</style>
